﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITAP.ContourBuilder.Components;
using ITAP.ContourBuilder.GUI;
using System.Windows.Forms;

using ITAP.Core.Calculations;
using ITAP.Core.Modelling;

namespace ITAP.ContourBuilder.Operations
{
    public class OperationSetElementLength: OperationWithSelectedElements
    {
        public override void Execute()
        {
            base.Execute();
            if (elements.Count == 0)
            {
                this.Cancel();
                return;
            }
            ContourElement element = elements[0];
            if (element.Height != 0)
            {
                MessageBox.Show("Длину можно задать только для неизогнутого элемента.");
                this.Cancel();
                return;
            }
            FormSetElementLength form = new FormSetElementLength(element.Length);
            if (form.ShowDialog() != System.Windows.Forms.DialogResult.OK || element.Length == form.Length)
            {
                this.Cancel();
                return;
            }

            if (form.LengthType == SetLengthFrom.Start)
            {
                ModelVector vector = element.Primitive.GetTangent(0);
                vector.Length = form.Length;
                ModelPoint endPoint = ModelCalculations.GetOffsetPoint(element.StartPoint, vector);
                if (element.EndConnectedComponent == null)
                    element.MoveEndPoint(endPoint);
                else
                    element.EndConnectedComponent.MoveTo(endPoint);
            }
            else
            {
                ModelVector vector = element.Primitive.GetTangent(0);
                vector = vector.Rotate(new Angle(Math.PI));
                vector.Length = form.Length;
                ModelPoint startPoint = ModelCalculations.GetOffsetPoint(element.EndPoint, vector);
                if (element.StartConnectedComponent == null)
                    element.MoveStartPoint(startPoint);
                else
                    element.StartConnectedComponent.MoveTo(startPoint);
            }
            this.Exit();
        }

        public override string ToString()
        {
            return "Задать длину элемента";
        }
    }
}
